import { GET_MENU, SET_MENU, MENU_ACTION } from '@/utils/Const';
import { Commit } from 'vuex';

import { asyncRoutes } from '@/router';

import { routesToMap, mappingRoutes } from '@/utils/Tools.js';

import { getMenuApi } from '@/api/system.api.js';


interface State {
  value: []
}

export default {
  namespaced: true,
  state: {
    value: []
  },
  getters: {
    [GET_MENU](state: State) {
      return state.value
    }
  },
  mutations: {
    [SET_MENU](state: State, payload): void {
      state.value = payload;
    }
  },
  actions: {
    async [MENU_ACTION](context: { commit: Commit }) {
      try {
        const res = await getMenuApi();
        // 路由转成map对象
        const routesMap = routesToMap(asyncRoutes);
        // 接口路由映射
        const routes = mappingRoutes(routesMap, res);
        // 首页转成子路由
        const dashboard = routesMap[''];
        routes[0].children = [dashboard];
        return new Promise((resolve) => {
          context.commit(SET_MENU, routes);
          resolve(routes);
        });
      } catch (error) {
        console.log('error', error);
      }
    }
  }
}